<template>
  <div class="info-outer-container">
    <div class="info-inner-container">
      <div class="container">
        <div class="left">
          <div class="header">
            <Header @updateActiveIndex="handleMenuClick" />
          </div>
          <div class="list">
            <div class="waterfall-container">
              <div v-for="(column, index) in columns" :key="index" class="waterfall-column">
                <div v-for="item in column" :key="item.id" class="waterfall-item" ref="setItemRef" @click="handleItemClick(item.id)">
                  <Item :item="item" />
                </div>
              </div>
            </div>
          </div>
          <div class="loadmore" @click="loadmore">点击加载更多</div>
        </div>
        <div class="right">
          <RightItem />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import Header from './header.vue'
import RightItem from './righitem.vue'
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { getInfoList } from '@/api/info'
import { useRouter } from 'vue-router'
const router = useRouter()
import Item from './item.vue'
// const list = ref([])

const items = ref([])
const columnCount = 2
const activeMenuIndex = ref(1)
const columns = ref(Array.from({ length: columnCount }, () => []))
const itemsRef = ref([])
const page = ref(1)
const loading = ref(false) // 控制加载状态
const hasMore = ref(true) // 判断是否还有更多数据
onMounted(() => {
  getData()
  // await nextTick()
  // assignItemsToColumns()
})
const loadmore = () => {
  getData()
}
const handleItemClick = (id) => {
  console.log(id, 'id')
  router.push(`/info/${id}`)
}
const handleMenuClick = (index) => {
  activeMenuIndex.value = index
  items.value = []
  columns.value = Array.from({ length: columnCount }, () => [])
  console.log('当前选择的菜单项索引:', index) // 1 表示足球，2 表示篮球
  page.value = 1
  loading.value = false
  hasMore.value = true
  getData()
}
const getData = async () => {
  if (loading.value || !hasMore.value) return
  loading.value = true
  try {
    const res = await getInfoList({ sport: activeMenuIndex.value, page: page.value, size: 50 })
    console.log(res.data.list, 'res')
    if (res.code === 200) {
      const newItems = res.data.list
      if (newItems.length === 0) {
        hasMore.value = false
      } else {
        items.value = items.value.concat(newItems)
        page.value++
        distributeToColumns(newItems)
        await nextTick() // 确保数据更新后 DOM 完成渲染
        // assignItemsToColumns()
        assignItemsToColumns(newItems)
      }
      // items.value = res.data.list
    }
  } catch (error) {
    console.log(error, 'error')
  } finally {
    loading.value = false
  }
}

// 初次渲染时，将新数据均匀分配到各列中
const distributeToColumns = (newItems) => {
  newItems.forEach((item, index) => {
    columns.value[index % columnCount].push(item)
  })
}
// 将 DOM 引用存储到 itemsRef 中
// const setItemRef = (el) => {
//   console.log(el, 'el')
//   if (el) {
//     itemsRef.value.push(el)
//   }
// }
const setItemRef = (el) => {
  console.log(el, 'el')
  if (el && !itemsRef.value.includes(el)) {
    itemsRef.value.push(el)
  }
}

const assignItemsToColumns = async (newItems) => {
  const allItems = document.querySelectorAll('.waterfall-item')

  // 临时保存所有 items 数据及其高度
  const tempItems = []
  allItems.forEach((itemElement, index) => {
    tempItems.push({
      ...items.value[index],
      height: itemElement.offsetHeight
    })
  })

  // 清空 columns
  columns.value = Array.from({ length: columnCount }, () => [])

  // 按高度重新分配 items 到列
  const columnHeights = Array(columnCount).fill(0)
  tempItems.forEach((item) => {
    const minHeightIndex = columnHeights.indexOf(Math.min(...columnHeights))
    columns.value[minHeightIndex].push(item)
    columnHeights[minHeightIndex] += item.height
  })
}

// 初次加载时从接口获取数据
// onMounted(async () => {
//   await fetchData()
//   // 等待 DOM 更新完毕

// })

// 监听 items 的变化，数据加载完后重新布局
watch(items, async (newItems, oldItems) => {
  console.log('Items updated:', newItems) // 调试：检查 items 数据
  if (newItems.length > oldItems.length) {
    await nextTick()
    console.log('update items')
    assignItemsToColumns()
  }
})
</script>
<style lang="scss" scoped>
.info-outer-container {
  width: 100%;
  height: 100%;
  background: #f5f7ff;
}
.info-inner-container {
  max-width: 1200px;
  margin: 0 auto;
}
.container {
  display: flex;
  justify-content: space-between;
  padding-top: 15px;
  .left {
    width: 854px;
    background: #fff;
    border-radius: 10px;
    .list {
      padding: 20px;
      min-height: 100vh;
    }
  }
}
.waterfall-container {
  display: flex;
  gap: 16px;
}

.waterfall-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.waterfall-item {
  // background-color: #f0f0f0;
  // padding: 16px;
  // box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-button {
  display: block;
  margin: 20px auto;
  padding: 10px 20px;
  font-size: 16px;
}
.loadmore {
  width: 80%;
  border: 1px solid #eee;
  text-align: center;
  height: 40px;
  line-height: 40px;
  margin: 0 auto 10px;
  border-radius: 10px;
  cursor: pointer;
  color: #666;
}
</style>
